package com.tets_09_08;

import java.security.MessageDigest;

public interface IDataBaseOperation {

    String informationEncryption(String info);
}

 class Adaptee {

    public String informationEncryptionByMD5(String info) {
        return MD5Util.MD5(info);
    }
}

 class EncryptionAdapter implements IDataBaseOperation {

    private Adaptee adaptee;

    public EncryptionAdapter() {
        adaptee = new Adaptee();
    }

    @Override
    public String informationEncryption(String info) {
        return adaptee.informationEncryptionByMD5(info);
    }
}


 class MD5Util {

    // MD5加密算法
    public static String MD5(String key) {
        char hexDigits[] = {
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
        };
        try {
            byte[] btInput = key.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }
}


 class User {

    // 用户昵称
    private String nickname;

    // 用户口令
    private String password;

    // 用户电话
    private String tel;

    // 用户邮箱
    private String email;

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}


 class Client {

    public static void main(String[] args) {

        User user = new User();
        user.setPassword("123456789");
        user.setEmail("syt@qq.com");

        // 针对接口编程
        IDataBaseOperation dataBaseOperation;
        // 实例化对象
        dataBaseOperation = new EncryptionAdapter();

        // 加密的用户密码
        String passwordEncryption = dataBaseOperation.informationEncryption(user.getPassword());

        // 加密的用户邮箱
        String emailEncryption = dataBaseOperation.informationEncryption(user.getEmail());

        System.out.println("加密前用户口令：" + user.getPassword() + "，加密后用户口令：" + passwordEncryption);

        System.out.println("加密前用户邮箱：" + user.getEmail() + ", 加密后用户邮箱：" + emailEncryption);
    }
}
